package info

import (
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/load"
	"log"
	"service/utils"
	"time"
)

type CpuInfos struct {
	LoadStat  LoadStat  `json:"loadStat"`
	CoreNum   int       `json:"coreNum"`
	CpuUse    []float64 `json:"cpuUse"`
	ModelName string    `json:"modelName"`
}

type LoadStat struct {
	Load1  float64 `json:"load1"`
	Load5  float64 `json:"load5"`
	Load15 float64 `json:"load15"`
}

//获取CPU信息
func GetCpuInfo() (interface{}, error) {

	//获取多个cpu使用信息
	percent, err := cpu.Percent(time.Millisecond*1000, true) //设置间隔时间
	if err != nil {
		log.Println("get cpu percent err!", err)
		return "", err
	}

	// cpu信息
	infos, err := cpu.Info()
	if err != nil {
		log.Println("get cpu info err!", err)
		return "", err
	}

	// 1分/5分/15分 cpu负载信息
	info, err := load.Avg()
	if err != nil {
		log.Println("get cpu avg err!", err)
	}

	for index, value := range percent {
		percent[index] = utils.Decimal(value, "2")
	}

	cpuInfo := CpuInfos{}

	cpuInfo.LoadStat.Load1 = info.Load1
	cpuInfo.LoadStat.Load5 = info.Load5
	cpuInfo.LoadStat.Load15 = info.Load15
	cpuInfo.CoreNum = len(percent)
	cpuInfo.CpuUse = percent
	cpuInfo.ModelName = infos[0].ModelName

	return cpuInfo, nil
}
